// directives/back-to-top.js
export const backToTop = {
  inserted(el, binding) {
    const threshold = binding.value || 300;
    
    // el.style.display = 'none';
    // el.style.position = 'fixed';
    // el.style.bottom = '20px';
    // el.style.right = '20px';
    // el.style.zIndex = '999';
    // el.style.cursor = 'pointer';
    
    const handleScroll = () => {
      if (window.scrollY > threshold) {
        el.style.display = 'block';
      } else {
        el.style.display = 'none';
      }
    };
    
    const scrollToTop = () => {
      // 平滑滚动逻辑（同上）
      const duration = 500;
      const startPosition = window.scrollY;
      const startTime = performance.now();
      
      const animateScroll = (currentTime) => {
        const elapsedTime = currentTime - startTime;
        const progress = Math.min(elapsedTime / duration, 1);
        window.scrollTo(0, startPosition - (startPosition * Math.pow(progress, 4)));
        
        if (progress < 1) {
          requestAnimationFrame(animateScroll);
        }
      };
      
      requestAnimationFrame(animateScroll);
    };
    
    el.addEventListener('click', scrollToTop);
    window.addEventListener('scroll', handleScroll);
    
    // 组件销毁时移除事件监听
    el.__backToTop = { handleScroll, scrollToTop };
  },
  unbind(el) {
    window.removeEventListener('scroll', el.__backToTop.handleScroll);
    el.removeEventListener('click', el.__backToTop.scrollToTop);
    delete el.__backToTop;
  }
};